import gulp from 'gulp';
import less from 'gulp-less';
import sourcemaps from 'gulp-sourcemaps';
import LessAutoprefix from 'less-plugin-autoprefix';
import LessPluginCleanCSS from 'less-plugin-clean-css';
import concat from 'gulp-concat';
import runSequence from 'run-sequence';
import es from'event-stream';

let enties = [
    {
        dest: './public/dest/css',
        config: {
            name: 'demo.css',
            src: [
                './public/stylesheets/demo.less'
            ]
        }
    }
];
let debug = false;

function handleError(err) {
    console.log(err.toString());
    this.emit('end');
}

gulp.task('less-process', () => {
    let autoprefix = new LessAutoprefix({ browsers: ['last 2 versions'] });
    let cleanCSSPlugin = new LessPluginCleanCSS({ advanced: true });

    let streamArr = [];

    for (let config of enties) {
        let stream = gulp.src(config.config.src)
            .pipe(less({
                plugins: debug ? [autoprefix] : [autoprefix, cleanCSSPlugin]
            }))
            .on('error', handleError)
            .pipe(concat(config.config.name));
        if (debug) {
            stream.pipe(sourcemaps.write());
        }
        stream.pipe(gulp.dest(config.dest));
        streamArr.push(stream);
    }
    return es.merge(streamArr);
});

gulp.task('build-less', (callback) => {
    debug = false;

    runSequence(['less-process'],
        callback);
});

gulp.task('build-less-dev', (callback) => {
    debug = true;

    runSequence(['less-process'],
        callback);
});

gulp.task('auto-compile-less', () => {
    let watcher = gulp.watch('./src/**/*.less', ['build-less-dev']);
});